package com.chenwb.concurrency.lock;

import java.util.concurrent.locks.ReentrantLock;

public class ReenterLockInterrupt implements Runnable {

	ReentrantLock reenteantLock = new ReentrantLock();

	/**
	 * 执行
	 */
	@Override
	public void run() {
		try {
			System.out.println(System.currentTimeMillis()/1000 + " " + Thread.currentThread().getName() + " 等待锁");
			reenteantLock.lockInterruptibly();
			System.out.println(System.currentTimeMillis()/1000 + " " +Thread.currentThread().getName() + " 加锁");
			Thread.sleep(2000);
			System.out.println(System.currentTimeMillis()/1000 + " " +Thread.currentThread().getName() + " 执行结束");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			if (reenteantLock.isHeldByCurrentThread()) {
				reenteantLock.unlock();
				System.out.println(System.currentTimeMillis()/1000 + " " +Thread.currentThread().getName() + " 解锁");
			}
		}
	}

	/**
	 * 其中一种执行结果：t1先执行
	 *1585794853 thread1 等待锁
	 * 1585794853 thread1 加锁
	 * 1585794853 thread2 等待锁
	 * java.lang.InterruptedException
	 * 	at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireInterruptibly(AbstractQueuedSynchronizer
	 * 	.java:898)
	 * 	at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly(AbstractQueuedSynchronizer
	 * 	.java:1222)
	 * 	at java.util.concurrent.locks.ReentrantLock.lockInterruptibly(ReentrantLock.java:335)
	 * 	at com.chenwb.concurrency.lock.ReenterLockInterrupt.run(ReenterLockInterrupt.java:16)
	 * 	at java.lang.Thread.run(Thread.java:748)
	 * 1585794855 thread1 执行结束
	 * 1585794855 thread1 解锁
	 * t2已经收到中断，加锁失败
	 *
	 * 另一种 t2先执行：
	 * 1585794503 thread2 等待锁
	 * 1585794503 thread2 加锁
	 * 1585794503 thread1 等待锁
	 * java.lang.InterruptedException: sleep interrupted
	 * 	at java.lang.Thread.sleep(Native Method)
	 * 	at com.chenwb.concurrency.lock.ReenterLockInterrupt.run(ReenterLockInterrupt.java:18)
	 * 	at java.lang.Thread.run(Thread.java:748)
	 * 1585794504 thread2 解锁
	 * 1585794504 thread1 加锁
	 * 1585794506 thread1 执行结束
	 * 1585794506 thread1 解锁
	 * 我们对t2线程在1s后进行了中断，t1正常执行结束，t2在sleep的时候收到中断抛出
	 * @param args
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws InterruptedException {
		ReenterLockInterrupt thread = new ReenterLockInterrupt();
		Thread t1 = new Thread(thread, "thread1");
		Thread t2 = new Thread(thread, "thread2");
		t1.start();
		t2.start();
		Thread.sleep(1000);
		t2.interrupt();

	}
}
